<template>
    <div class="container">
        <div class="toolbar">
            <el-select v-model="search.groupId" placeholder="请选择组" style="width: 140px;">
                <el-option v-for="item in groupOptions" :key="item.id" :label="item.groupName" :value="item.id" />
            </el-select>
            <el-input v-model="search.name" placeholder="号码名称" style="width: 120px; margin: 0 12px;" />
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button @click="openAddDialog" style="margin-left: 8px;">添加</el-button>
            <el-button @click="onBatchAdd" style="margin-left: 8px;">M码出N添加</el-button>
        </div>
        <el-table :data="filteredNumbers" border stripe class="number-table" height="calc(100vh - 220px)">
            <el-table-column prop="groupName" label="组名称" min-width="160" align="center" />
            <el-table-column prop="name" label="号码名称" min-width="120" align="center" />
            <el-table-column label="操作" align="center" min-width="140">
                <template #default="scope">
                    <el-button type="danger" size="small" @click="removeNumber(scope.row)">删除</el-button>
                    <el-button size="small" @click="viewNumber(scope.row)">查看</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog v-model="batchAddDialogVisible" title="M码出N码" width="420px">
            <div style="margin-bottom: 18px;">
                <div style="margin-bottom: 10px; font-weight: 500;">M码：</div>
                <el-radio-group v-model="batchAddForm.m" @change="onMChange">
                    <el-radio v-for="m in mOptions" :key="m" :label="m" class="m-radio">{{ m }}</el-radio>
                </el-radio-group>
            </div>
            <div style="margin-bottom: 18px;">
                <div style="margin-bottom: 10px; font-weight: 500;">N码：</div>
                <el-checkbox-group v-model="batchAddForm.n" class="n-checkbox-group">
                    <el-checkbox v-for="n in nOptions" :key="n" :label="n" class="n-checkbox">{{ n }}</el-checkbox>
                </el-checkbox-group>
            </div>
            <template #footer>
                <el-button @click="batchAddDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="onBatchAddOk">确定</el-button>
            </template>
        </el-dialog>
        <el-dialog v-model="addDialogVisible" title="添加号码" width="350px" @close="resetAddDialog">
            <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="80px">
                <el-form-item label="组名称" prop="group">
                    <el-select v-model="addForm.groupId" placeholder="请选择组">
                        <el-option v-for="item in groupOptions" :key="item.id" :label="item.groupName"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="号码名称" prop="name">
                    <el-input v-model="addForm.name" maxlength="20" show-word-limit placeholder="请输入号码名称" />
                </el-form-item>
                <el-form-item label="号码" prop="numbers">
                    <el-input type="textarea" v-model="addForm.numbers" show-word-limit placeholder="请输入号码名称" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitAddForm">确定</el-button>
            </template>
        </el-dialog>

        <el-dialog v-model="viewNumberDialogVisible" title="查看号码" width="400px" class="number-dialog">
            <div class="enhanced-toolbar">
                <el-button size="small" @click="copyNumbers" style="margin-left: 8px;">复制</el-button>
            </div>
            <div class="number-list beautified-list">
                <template v-for="(row, idx) in formattedNumbers" :key="idx">
                    <div class="number-row">{{ row }}</div>
                </template>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

import { getGroup } from '@/api/Omission/group'
import { getNumber, addNumber, deleteNumber, getNumbers, addMN } from '@/api/Omission/number'

const groupOptions = ref([])


const search = reactive({
    groupId: "",
    name: ""
})

const init = async () => {
    const res = await getGroup()
    if (res.code === 'S') {
        groupOptions.value = res.data || []
    } else {
        ElMessage.error(res.message || '获取号码组列表失败')
    }
}
init()

const filteredNumbers = ref([])

const onSearch = async () => {
    const formData = {}
    if (search.groupId) {
        formData.groupId = search.groupId
    }
    if (search.name) {
        formData.name = search.name
    }
    const res = await getNumber(formData)
    if (res.code === 'S') {
        filteredNumbers.value = res.data || []
        refreshFormData.value = { ...formData }
    } else {
        ElMessage.error(res.message || '获取号码列表失败')
    }
}

const refreshFormData = ref({})
const refresh = async () => {
    const res = await getNumber(refreshFormData.value)
    if (res.code === 'S') {
        filteredNumbers.value = res.data || []
    } else {
        ElMessage.error(res.message || '获取号码列表失败')
    }
}

// 添加号码弹窗
const addDialogVisible = ref(false)
const addForm = reactive({ groupId: '', name: '', numbers: '' })
const addFormRef = ref()
const addRules = {
    groupId: [{ required: true, message: '请选择组', trigger: 'change' }],
    name: [{ required: true, message: '请输入号码名称', trigger: 'blur' }],
    numbers: [{ required: true, message: '请输入号码', trigger: 'blur' }]
}

const openAddDialog = async () => {
    addDialogVisible.value = true
}
const resetAddDialog = async () => {
    addForm.groupId = ''
    addForm.name = ''
    addForm.numbers = ''
    addFormRef.value && addFormRef.value.clearValidate()
}
const submitAddForm = async () => {
    await addFormRef.value.validate(async (valid) => {
        if (valid) {
            const formData = {
                groupId: addForm.groupId,
                groupName: groupOptions.value.find(g => g.id === addForm.groupId)?.groupName || '',
                name: addForm.name,
                numbers: addForm.numbers
            }
            const res = await addNumber(formData)
            if (res.code !== 'S') {
                ElMessage.error(res.message || '添加失败')
                return
            }
            ElMessage.success('添加成功')
            addDialogVisible.value = false
            await resetAddDialog()
            await refresh()
        }
    })
}

const removeNumber = async (row) => {
    const res = await deleteNumber(row)
    if (res.code !== 'S') {
        ElMessage.error(res.message || '删除失败')
        return
    }
    ElMessage.success('删除成功')
    await refresh()
}


const viewNumberDialogVisible = ref(false)
const numberString = ref("")
const formattedNumbers = ref([])

const viewNumber = async (row) => {
    const params = { id: row.id }
    const res = await getNumbers(params)
    if (res.code === 'S') {
        // 假设res.data.numbers为字符串
        numberString.value = res.data.numbers || ''
        formattedNumbers.value = numberString.value.split(' ').reduce((acc, cur, idx) => {
            if (idx % 5 === 0) acc.push([])
            acc[acc.length - 1].push(cur)
            return acc
        }, []).map(arr => arr.join(' '))
        viewNumberDialogVisible.value = true
    } else {
        ElMessage.error(res.message || '获取号码详情失败')
    }
}

const copyNumbers = async () => {
    try {
        await navigator.clipboard.writeText(numberString.value)
        ElMessage.success('已复制到剪贴板')
    } catch {
        ElMessage.error('复制失败')
    }
}

// M码出N码弹窗相关
const batchAddDialogVisible = ref(false)
const batchAddForm = reactive({ m: 1, n: [] })
const mOptions = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const nOptions = ref([0, 1])

const onMChange = (val) => {
    if (val === 1) nOptions.value = [0, 1]
    else if (val === 2) nOptions.value = [0, 1, 2]
    else nOptions.value = [0, 1, 2, 3]
    // 自动清理不合法的n
    batchAddForm.n = batchAddForm.n.filter(n => nOptions.value.includes(n))
}

const onBatchAdd = () => {
    batchAddDialogVisible.value = true
    // 初始化N码选项
    onMChange(batchAddForm.m)
}

const onBatchAddOk = async () => {
    const formData = {
        m: batchAddForm.m,
        ns: batchAddForm.n
    }
    const res = await addMN(formData)
    if (res.code === 'S') {
        ElMessage.success('M码出N码添加成功')
        batchAddDialogVisible.value = false
        await refresh()
    } else {
        ElMessage.error(res.message || 'M码出N码添加失败')
    }
}

// 粘贴功能：将剪贴板内容粘贴到添加号码弹窗的号码输入框
const pasteNumbers = async () => {
    try {
        const text = await navigator.clipboard.readText();
        addForm.numbers = text;
        ElMessage.success('已粘贴到输入框');
    } catch {
        ElMessage.error('粘贴失败');
    }
}
</script>

<style scoped lang="scss">
.dialog-toolbar {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 8px;
}

.enhanced-toolbar {
    gap: 8px;
    background: #f7f8fa;
    border-radius: 8px;
    padding: 6px 10px 6px 0;
    box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.04);
}

.number-list {
    max-height: 300px;
    overflow-y: auto;
    font-family: monospace;
    font-size: 15px;
    line-height: 1.8;
    word-break: break-all;
    background: #f9fafb;
    border-radius: 8px;
    padding: 10px 12px;
    box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.03);
}

.beautified-list .number-row {
    padding: 2px 0 2px 4px;
    border-bottom: 1px dashed #e5e6eb;
    transition: background 0.2s;
}

.beautified-list .number-row:last-child {
    border-bottom: none;
}

.number-dialog {
    --el-dialog-border-radius: 12px;
}

.m-radio {
    margin-right: 4px !important;
    padding: 0 2px !important;
    font-size: 13px !important;
    min-width: 28px;
    height: 22px;
    line-height: 20px;
}

::v-deep(.m-radio .el-radio__label) {
    padding: 0 2px !important;
    font-size: 13px !important;
}

::v-deep(.m-radio .el-radio__input) {
    width: 15px !important;
    height: 15px !important;
    margin-right: 2px !important;
}

.n-checkbox-group {
    display: flex;
    flex-wrap: wrap;
    gap: 0 2px;
    align-items: center;
}

.n-checkbox {
    margin-right: 2px !important;
    margin-bottom: 0 !important;
    padding: 0 0 !important;
    font-size: 13px !important;
    min-width: 32px;
    height: 24px;
    line-height: 22px;
}

::v-deep(.n-checkbox .el-checkbox__label) {
    padding: 0 2px !important;
    font-size: 13px !important;
}

::v-deep(.n-checkbox .el-checkbox__input) {
    width: 16px !important;
    height: 16px !important;
    margin-right: 2px !important;
}
</style>

<style scoped lang="scss">
@use "@/assets/global.scss" as *;

.toolbar {
    display: flex;
    align-items: center;
    margin-bottom: 18px;
    flex-wrap: wrap;
    gap: 8px;
}

.number-table {
    background: #fcfcfc;
    border-radius: 6px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
}
</style>